<?php

class UsuariosController extends Zend_Controller_Action
{

    public function init()
    {
        $this->view->voltar = $this->view->url(array(
            'module'=>$this->view->originalModule,
            'controller'=>$this->view->originalController, 
            'action'=>'index'));
        $this->view->title = "Cadastro de usuários";
    }

    public function indexAction()
    {
        $usuarios = new Usuarios();
        $this->view->usuarios = $usuarios->fetchAll(null,'nome');
    }

    public function loginAction()
    {
        
        $form    = new Application_Form_Login();

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost()) && $form->getValue('user_id')) {
                $salt    = 'PZzQ~dbFf%[Ojm+eFoc1c191C';
                $auth    = Zend_Auth::getInstance();
                $user_id    = $form->getValue('user_id');
                $senha      = $form->getValue('senha');
                
                $mdl_user = new mdlUser();
                $mdl_user = $mdl_user->find($user_id)->current();
                
                if($mdl_user){
                    
                    $gesac = new Usuarios();
                    $gesac = $gesac->find($user_id)->current();
                    if(md5($senha.$salt) == $mdl_user['password']){
                        $result = $this->login($gesac['nome'], $gesac['id']);
                    } else $result = $this->login($gesac['nome'],0);
                }
                
                if ($result->isValid()) {
                    $this->_redirect('index/index');
                }
                $this->view->messages = array('Login failed');
            }
        }

        if ($this->_hasParam('url')) {
            $path = str_replace('index.php','', $_SERVER['SCRIPT_NAME']);
            $url = base64_decode($this->_getParam('url'));
            $url = str_replace($path, '', $url);
            $session->url = $url;
        }
        $this->view->form = $form;
        
    }


    public function addAction()
    {
        $form = new Application_Form_Usuario();
        $form->submit->setLabel('Adicionar');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $nome = $form->getValue('nome');
                $apelido = $form->getValue('apelido');
                $senha = $form->getValue('senha');
                $usuarios = new Usuarios();
                $usuarios->addUsuario($nome, $apelido, $senha);
                $this->_redirect('index');
            } else {
                $form->populate($formData);
            }
        }
        $this->render('add');
    }

    public function editAction()
    {
        $form = new Application_Form_Usuario();
        $form->submit->setLabel('Salvar');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $id = (int)$form->getValue('id');
                $nome = $form->getValue('nome');
                $apelido = $form->getValue('apelido');
                $senha = $form->getValue('senha');
                $usuarios = new Usuarios();
                $usuarios->updateUsuario($id, $nome, $apelido, $senha);
                $this->_redirect('index');
            } else {
                $form->populate($formData);
            }
        } else
        {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $usuarios = new Usuarios();
                $form->populate($usuarios->getUsuario($id));
            }
        }
        $this->render('edit');

    }

    public function deleteAction()
    {
        $id = $this->getRequest()->getParam('id', 0);
        $usuarios = new Usuarios();
        if ($this->getRequest()->isPost())
        {
            $resposta = $this->getRequest()->getPost('resposta');
            if ($resposta == 'Sim') {
                $usuarios->deleteUsuario($id);
            }
            $this->_redirect('index');
        } 
        $usuario = $usuarios->getUsuario($id);
        $this->view->action = 'default/usuarios/delete';
        $this->view->pergunta = 'Deseja excluir o usuário: <b>'.$usuario->nome.'?';
        $this->render('confirm');
    }
    
    public function logoutAction()
    {
        $session = new Zend_Session_Namespace('data');
        $session->unsetAll();
                
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect( "default/index/index" );
    }    
    
    private function login($username, $id)
    {
        $auth    = Zend_Auth::getInstance();
        $db      = Zend_Db_Table::getDefaultAdapter('gesac');
        $adapter = new Tri_Auth_Adapter_DbTable($db, 'usuario', 'nome', 'id');

        $adapter->getDbSelect()->where('status = ?', 'active');

        $adapter->setIdentity($username)
                ->setCredential($id);

        return $auth->authenticate($adapter);
    }
}

